//
//  YBCloudComputerViewModel.swift
//  Moonlight
//
//  Created by Penlon Kim on 2023/6/8.
//  Copyright © 2023 Moonlight Game Streaming Project. All rights reserved.
//

import UIKit
import HandyJSON
import SwiftyJSON

class YBCloudComputerViewModel: BaseViewModel {
    
    lazy var orderInfoVosModels = [YBOrderInfoVosModel]()
    lazy var buyModels = [YBBuyModel]()
    lazy var detailModel = YBGoodsDetailModel()
}

// MARK: - 网络请求
extension YBCloudComputerViewModel {
    
    /// 获取订单信息-手机端
    func req_UserOrderInfo(handler: @escaping BKResultHandler) {
        self.getReq(path: NetApiPort.User.userOrderInfo, handler: handler)
    }
    
    /// 关机
    func req_ClosePC(handler: @escaping BKResultHandler) {
        self.getReq(path: NetApiPort.VirtualMachine.turnOff, handler: handler)
    }
    
    /// 查询SSE
    func req_CheckSSEForPC(_ vmName: String, handler: @escaping BKResultHandler) {
        self.getReq(path: NetApiPort.VirtualMachine.check + "/" + vmName, handler: handler)
    }
    
    /// 配对
    func req_Pair(_ params: [String: String], handler: @escaping BKResultHandler) {
        self.postReq(path: NetApiPort.VirtualMachine.moonlight, params: params, handler: handler)
    }
    
    /// 获取商品详情
    func req_GetInfo(_ goodsId: String, handler: @escaping BKResultHandler) {
        self.getReq(path: NetApiPort.Order.getInfo + "/" + goodsId, handler: handler)
    }
    
    /// 调保存快照，再接着调新增订单，在调用预支付
    func startPay(buyModel: YBBuyModel, payType: Int, handler: @escaping BKPayHandler) {
        var params = ["amount": buyModel.priceTag,
                      "goodsId": buyModel.goodsId,
                      "goodsLadderId": buyModel.id,
                      "goodsName": self.detailModel.goodsName,
                      "payAmount": buyModel.priceTag.stringValue(),
                      "payMethod": buyModel.buy,
                      "payMethodPrice": buyModel.price,
                      "payType": payType,
                      "payNum": 1] as [String : Any]
        
        // 内购额外需要的
        if payType == 3 {
            params["productId"] = buyModel.productId
        }
        self.req_SnapShot(params) { ok, obj, msg, code in
            if ok {
                guard let js = obj as? JSON,
                      let data = js[NetDataKey].dictionaryObject,
                      let snapModel = YBSnapModel.deserialize(from: data) else { return }
                
                let params = ["orderAmount": snapModel.orderAmount,
                              "orderSn": snapModel.orderSn,
                              "payAmount": snapModel.payAmount] as [String : Any]
                if payType == 2 {
                    self.req_WxPay(params) { ok, obj, msg, code in
                        if ok {
                            // 微信支付参数
                             let js = obj as? JSON
                            let parm = js?[NetDataKey]["parm"].stringValue
                            handler(parm)
                        } else {
                            HintTool.toast(msg)
                        }
                    }
                }else if payType == 1 {
                    self.req_AliPay(params) { ok, obj, msg, code in
                        if ok {
                            // 支付宝支付参数
                            let js = obj as? JSON
                            let parm = js?[NetDataKey]["parm"].stringValue
                            handler(parm)
                        } else {
                            HintTool.toast(msg)
                        }
                    }
                } else {
                    // 苹果支付
                    let apple_params = ["receipt": buyModel.receipt,
                                  "orderSn": snapModel.orderSn] as [String : Any]
                    self.req_ApplePay(apple_params) { ok, obj, msg, code in
                        if ok {
                            handler(msg)
                        } else {
                            HintTool.toast(msg)
                        }
                    }
                }
            } else {
                // 请求错误了
                HintTool.toast(msg)
            }
        }
    }
    
    /// 保存快照
    func req_SnapShot(_ params: [String : Any], handler: @escaping BKResultHandler) {
        self.postReq(path: NetApiPort.Pay.snapShot, params: params, handler: handler)
    }
    
    /// 新增订单（弃用）
    func req_CreateOrder(_ params: [String : Any], handler: @escaping BKResultHandler) {
        self.postReq(path: NetApiPort.Pay.createOrder, params: params, handler: handler)
    }
    
    /// 预支付（微信）
    func req_WxPay(_ params: [String : Any], handler: @escaping BKResultHandler) {
        self.postReq(path: NetApiPort.Pay.wxPay, params: params, handler: handler)
    }
    
    /// 预支付（支付宝）
    func req_AliPay(_ params: [String : Any], handler: @escaping BKResultHandler) {
        self.postReq(path: NetApiPort.Pay.aliPay, params: params, handler: handler)
    }
    
    /// 苹果支付
    func req_ApplePay(_ params: [String : Any], handler: @escaping BKResultHandler) {
        self.postReq(path: NetApiPort.Pay.applePay, params: params, handler: handler)
    }
    
    /// 重置虚拟机状态
    func req_Reset(_ handler: @escaping BKResultHandler) {
        self.getReq(path: NetApiPort.VirtualMachine.reset, handler: handler)
    }
    
    /// 故障报修
    func req_Gzbx(_ params: [String : Any], handler: @escaping BKResultHandler) {
        self.postReq(path: NetApiPort.VirtualMachine.save, params: params, handler: handler)
    }
}
